<template>
	<view class="content">
		<!-- <view class="login">登录</view> -->
		<img :src="avatarUrl || '../../static/tx.jpg'" alt="用户头像" mode="aspectFill" class="pic" @click="choosepic()">
		<view class="info">
			<view>
				姓名
				<input type="text" placeholder="请输入姓名" v-model="username"/>
			</view>
			<view>
				联系方式
				<input type="text" placeholder="请输入联系方式" v-model="phoneNum"/>
			</view>
			<view>
				身份证号码
				<input type="text" placeholder="请输入身份证号码" v-model="IdentifyNum"/>
			</view>
			<view>
				工作单位
				<input type="text" placeholder="请输入工作单位" v-model="occupation"/>
			</view>
		</view>
		<button class="login_button" @click="edit()">确认修改</button>
	</view>
</template>

<script>
	import {update} from '@/api/userApi.js'
	export default {
		data() {
			return {
				title: 'Hello',
				isAgreed:false,
				username:'',
				phoneNum:'',
				IdentifyNum:'',
				occupation:'',
				avatarUrl:'/static/tx.jpg',
				userId:'',
				createAt:'',
				defaultAvatar: '/static/tx.jpg'
			}
		},
		onLoad() {
		    // 页面加载时读取缓存数据
		    this.loadCachedData();
		  },
		methods: {
			loadCachedData() {
						      uni.getStorage({
						        key: 'user',
						        success: (res) => {
									console.log(res.data)
						          // 将缓存数据覆盖到data中
								  this.userId=res.data.userId;
						          this.avatarUrl = res.data.avatarUrl||this.defaultAvatar;
						          this.username = res.data.nickName;
						          this.phoneNum = res.data.phone;
								  this.IdentifyNum=res.data.idCard;
								  this.occupation=res.data.unit;
								  this.createAt=res.data.createAt;
						        },
						        fail: (err) => {
						          console.error('读取缓存失败', err);
						        }
						      });
			},
		    toggleAgree() {
		      this.isAgreed = !this.isAgreed; // 切换状态
			  
		    },
			contract(){
				const navigator = uni || wx;
				      if (navigator?.navigateTo) {
				        navigator.navigateTo({
				          url: '/pages/usercontac/usercontac'
				        });
				      } else {
				        console.error('导航 API 不可用');
				      }
			},
			// 确认修改并更新数据库
			   async edit() {
			     this.loading = true;
			     
			     try {
			       // 1. 参数校验
			       if (!this.userId) {
			         throw new Error('用户ID不能为空');
			       }
			   
			       // 2. 构建数据
			       const userData = {
			         userId: this.userId,
			         nickName: this.username,
			         phone: this.phoneNum,
			         idCard: this.IdentifyNum,
			         unit: this.occupation,
			         avatarUrl: this.avatarUrl,
					 createAt:this.createAt,
			       };
			       console.log('提交数据:', userData);
			   
			       // 3. 调用接口
			       const res = await update(userData);
			   
			       // 4. 处理响应（根据实际结构调整）
			       if (res?.code == '200' || res?.data?.code == '200') {
			         uni.showToast({ title: '更新成功', icon: 'success' });
					 // 触发全局事件
					if (this.$eventBus) {
					        this.$eventBus.$emit('user-data-updated', userData);
					      } else {
					        console.warn('事件总线未初始化，使用备用更新方式');
					        this.updateLocalData(userData);
					      }
					// 更新本地缓存
			         uni.setStorageSync('user', userData);
			       } else {
			         throw new Error(res?.message || '更新失败');
			       }
			     } catch (error) {
			       console.error('更新失败:', {
			         message: error.message,
			         response: error.response?.data,
			       });
			     } finally {
			       this.loading = false;
			     }
			   },
			    updateLocalData(data) {
			       const pages = getCurrentPages();
			       if (pages.length > 1) {
			         const prevPage = pages[pages.length - 2];
			         if (prevPage.$vm && prevPage.$vm.handleUserUpdate) {
			           prevPage.$vm.handleUserUpdate(data);
			         }
			       }
			     },
			async choosepic() {
			      try {
			        const res = await uni.chooseImage({
			          count: 1,
			          sizeType: ['compressed'],
			          sourceType: ['album', 'camera']
			        });
			        this.avatarUrl = res.tempFilePaths[0];
			        this.uploadAvatar(this.avatarUrl);
			      } catch (err) {
			        console.error('选择头像失败:', err);
			        uni.showToast({ title: '选择头像失败', icon: 'none' });
			      }
			    },
			    uploadAvatar(filePath) {
			      uni.showLoading({ title: '上传中...' });
			      uni.uploadFile({
			        url: 'https://tcb-api.tencentcloudapi.com/upload',
			        filePath: filePath,
			        name: 'avatar',
			        success: (res) => {
			          uni.hideLoading();
			          uni.showToast({ title: '上传成功' });
			        },
			        fail: (err) => {
			          uni.hideLoading();
			          uni.showToast({ title: '上传失败', icon: 'none' });
			        }
			      });
			    }
				},
				
	}
</script>

<style>
	.content{
		position: relative;
	}
	.content .login{
		text-align: center;
	}
	.content .pic{
		position: absolute;
		width: 150px;
		height: 150px;
		left: 120px;
		top: 50px;
		border-radius: 150px;
		border: 1px solid silver; /* 红色边框便于调试 */
	}
	.content .info{
		position: absolute;
		top: 250px;
		left: 30px;
	}
	.content .info view{
		margin-bottom: 10px;
	}
	.content .info view input{
		border: 1px solid #F6F6F6;
		width: 300px;
		padding: 2px;
		margin: 5px;
		border-radius: 5px;
		background-color: #F6F6F6;
		
	}
	.content .info view text{
		color: red;
	}
	.content .agree{
		position: absolute;
		top: 540px;
		left: 30px;
	}
	.agree .dh{
		color: #FA816B;
		float: right;
	}
	.content .login_button{
		position: absolute;
		top: 540px;
		left: 50px;
		width: 240px;
		height: 55px;
		line-height: 55px;
		background: linear-gradient(to right,#F8900D,#FD623C);
		border-radius: 50px;
		color: white;
		font-size: 15px;
		font-weight: 700;
		font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
	}
	.custom-checkbox .agreed-bg{
		background-color: #FA6146;
	}
</style>
